package com.youdoneed.user.photo;

import com.querydsl.sql.SQLQuery;
import com.querydsl.sql.SQLQueryFactory;
import com.querydsl.sql.dml.SQLInsertClause;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.GlobalIdWorker;
import com.youdoneed.base.pagination.Page;
import com.youdoneed.base.pagination.Paging;
import com.youdoneed.common.feign.FileFeignClient;
import com.youdoneed.user.application.QueryHelper;
import com.youdoneed.user.model.Photo;
import com.youdoneed.user.query.QPhoto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 照片服务实现类。
 *
 * @author Ewing
 * @date 2017.2.8
 */
@Service
@Transactional
public class PhotoServiceImpl implements PhotoService {
    private final Logger logger = LoggerFactory.getLogger(PhotoServiceImpl.class);

    @Autowired
    private SQLQueryFactory queryFactory;

    private QPhoto qPhoto = QPhoto.Photo;

    @Autowired
    private FileFeignClient fileFeignClient;

    /**
     * 添加照片。
     */
    @Override
    public long addPhoto(Photo photo) {
        if (photo == null || !StringUtils.hasText(photo.getUserId())
                || !StringUtils.hasText(photo.getUrl())) {
            throw new AppException("Photo info is empty.");
        }
        photo.setPhotoId(GlobalIdWorker.nextString());
        photo.setCreateTime(new Date());
        return queryFactory.insert(qPhoto)
                .populate(photo)
                .execute();
    }

    @Override
    public long addPhotos(String userId, Photo[] photos) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("UserInformationIsEmpty");
        }
        SQLInsertClause insert = queryFactory.insert(qPhoto);
        for (Photo photo : photos) {
            if (photo == null || !StringUtils.hasText(photo.getUrl())) {
                throw new AppException("Photo info is empty.");
            }
            photo.setPhotoId(GlobalIdWorker.nextString());
            photo.setUserId(userId);
            photo.setCreateTime(new Date());
            insert.populate(photo)
                    .addBatch();
        }
        return insert.isEmpty() ? 0 : insert.execute();
    }

    /**
     * 根据ID获取照片。
     */
    @Override
    public Photo getPhoto(String photoId) {
        if (!StringUtils.hasText(photoId)) {
            throw new AppException("Photo id is empty.");
        }
        return queryFactory.selectFrom(qPhoto)
                .where(qPhoto.photoId.eq(photoId))
                .fetchOne();
    }

    /**
     * 获取全部照片。
     */
    @Override
    public Page<Photo> userPhotos(String userId, Paging paging) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("User id is empty.");
        }
        SQLQuery<Photo> query = queryFactory.selectFrom(qPhoto)
                .where(qPhoto.userId.eq(userId))
                .orderBy(qPhoto.createTime.desc());
        return QueryHelper.queryPage(paging, query);
    }

    /**
     * 删除照片。
     */
    @Override
    public long deletePhoto(String userId, String photoId) {
        if (!StringUtils.hasText(userId) || !StringUtils.hasText(photoId)) {
            throw new AppException("Photo id or user id is empty.");
        }
        // 用户不能删除别人的照片
        Photo oldPhoto = getPhoto(photoId);
        if (!userId.equals(oldPhoto.getUserId())) {
            throw new AppException("This photo is not yours.");
        }
        fileFeignClient.deleteByUrl(oldPhoto.getUrl());
        return queryFactory.delete(qPhoto)
                .where(qPhoto.photoId.eq(photoId))
                .execute();
    }

    /**
     * 更新照片。
     */
    @Override
    public long updatePhoto(String userId, Photo photo) {
        if (photo == null || !StringUtils.hasText(photo.getUserId())
                || !StringUtils.hasText(photo.getUrl())) {
            throw new AppException("Photo info is empty.");
        }
        // 用户不能修改别人的照片
        Photo oldPhoto = getPhoto(photo.getPhotoId());
        if (!userId.equals(oldPhoto.getUserId())) {
            throw new AppException("This photo is not yours.");
        }
        return queryFactory.update(qPhoto)
                .populate(photo)
                .where(qPhoto.photoId.eq(photo.getPhotoId()))
                .execute();
    }

}
